<template>
  <NotificationDrawer  :user-id="userId"/>
  <router-view />
</template>

<script setup>
import useSettingsStore from '@/store/modules/settings'
import { handleThemeStyle } from '@/utils/theme'
import NotificationDrawer from "@/views/order/components/Notice/NotificationDrawer.vue";
import useUserStore from "@/store/modules/user.js";
import {getMessageByName} from "@/api/system/message.js";
import { getUserProfile } from "@/api/system/user";
import {useWebSocket} from "@/store/websocket.js";


const userStore = useUserStore()
// 假设 userStore.id 是用户的唯一标识符
const userId = computed(() => userStore.id);
const websocketStore = useWebSocket()

const initWebSocketConnection = () => {

    websocketStore.initWebSocket(userId.value)
    console.log('App.Vue页面WebSocket连接已建立', userId.value)

}



onMounted(async () => {

   if(userStore.token){
     initWebSocketConnection()
   }

  nextTick(() => {
    // 初始化主题样式
    handleThemeStyle(useSettingsStore().theme)
  })
})

watch(
    () => userStore.token,
    (newVal) => {
      if (newVal) {
        initWebSocketConnection()
      } else {
        websocketStore.closeWebSocket()
        console.log('用户登出，WebSocket已断开')
      }
    }
)

// 监听用户ID变化（切换账号时）
watch(userId, (newId) => {
  if (newId && userStore.token) {
    websocketStore.reconnectWebSocket(newId)
  }
})

onUnmounted(() => {
  websocketStore.closeWebSocket()
})

</script>
